package rpcservicetask;

import rpcserver.RpcServerCenter;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.Socket;

public class ServiceTask implements Runnable {

	Socket client = null;

	public ServiceTask(Socket client) {
		this.client = client;
		System.out.println(client.getLocalPort()+"accept success");
	}

	@Override
	public void run() {
		ObjectInputStream input = null;
		ObjectOutputStream output = null;
		try {
			input = new ObjectInputStream(client.getInputStream());
			String serviceName = input.readUTF();
			String methodName = input.readUTF();
			Class<?>[] parameterTypes = (Class<?>[]) input.readObject();
			Object[] arguments = (Object[]) input.readObject();
			Class serviceClass = RpcServerCenter.getServiceClass(serviceName);
			if (serviceClass == null) {
				throw new ClassNotFoundException(serviceName + " not found");
			}
			Method method = serviceClass.getMethod(methodName, parameterTypes);
			Object result = method.invoke(serviceClass.newInstance(), arguments);
			output = new ObjectOutputStream(client.getOutputStream());
            output.writeObject(result);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			
			try {
				input.close();
				output.close();
				client.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}

	}

}
